import axios from 'axios'

let online_api = 'http://api.51pinzhi.cn/api/' // 线上接口地址
let offline_api = 'http://api.51pinzhi.cn/api/' // 测试接口地址

function successParse (res) {
  try {
    return JSON.parse(res.data)
  } catch (e) {
    return res.data
  }
}

function errorParse (error) {
  if (error.response) {
    switch (error.response.status) {
      // 系统错误
      default:
        return Promise.reject({code: error.response.status, msg: '传输异常，请稍后再试'})
    }
  } else {
    return Promise.reject({msg: '传输异常，请稍后再试'})
  }
}

function send (url, method, body, options) {
  /* 匹配线上环境和测试环境
   * 测试环境打包执行 【build-test】
   * 线上环境打包执行【build】
   */
  switch (process.env.NODE_ENV) {
    case 'production':
      if (!url.startsWith('http')) {
        url = online_api + url
      }
      break
    case 'testing':
    case 'development':
      if (!url.startsWith('http')) {
        url = offline_api + url
      }
      break
    default:
      if (!url.startsWith('http')) {
        url = offline_api + url
      }
      break
  }
  const opts = {...options}
  opts.headers = {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    'Authentication': window.$globalHub.$store.state.auth.authInfo.Token || '',
    ...opts.headers
  }
  switch (method) {
    case 'get':
      return axios.get(url, opts)
        .then(res => successParse(res))
        .catch(error => errorParse(error))
    case 'post':
      return axios.post(url, body, opts)
        .then(res => successParse(res))
        .catch(error => errorParse(error))
  }
}

export default {
  get (url, options) {
    return send(url, 'get', null, options)
  },
  post (url, body, options) {
    return send(url, 'post', body, options)
  }
}
